package com.coinland.study.view;

import android.content.res.AssetManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.coinland.study.R;
import com.coinland.study.base.BaseActivity;
import com.coinland.study.util.Calculate;
import com.coinland.study.util.DisplayUtils;
import com.coinland.study.util.ToastUtil;
import com.coinland.study.widgt.CircleIndicatorView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;

/**
 * 类描述:  使用Webview加载html
 * 创建人:  shenZ
 * 创建时间: 2020/3/23
 * 联系方式: 252079249@qq.com
 * 修改时间: 2020/3/23
 */
public class WebViewActivity extends BaseActivity {

    private String TAG = getClass().getSimpleName();

    private List<String> idList = new ArrayList();
    private int[] locationArray;

    @BindView(R.id.webView)
    public WebView webView;

    @BindView(R.id.indicatorView)
    public CircleIndicatorView indicatorView;

    private int height = 0 ;

    @Override
    public int getLayoutId() {
        return R.layout.activity_webview;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initView() {

        // Chrome内核浏览器
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 加载完成后  进行操作
                List<String> ss = new ArrayList<>();
                for (String string : idList) {
                    ss.add("'"+string+"'");
                }
                Log.i(TAG,Arrays.toString(ss.toArray()));
                webView.loadUrl("javascript:switchdata(" + Arrays.toString(ss.toArray()) + ")");
            }

            // 放大监听
            @Override
            public void onScaleChanged(WebView view, float oldScale, float newScale) {
                super.onScaleChanged(view, oldScale, newScale);

                float scale =  newScale/oldScale;
                for(int i=0;i< locationArray.length;i++){
                    int temp = locationArray[i];
                    locationArray[i] = (int) (temp * scale);
                }

            }
        });
        WebSettings setting = webView.getSettings();
        //与js交互必须设置
        setting.setJavaScriptEnabled(true);
        // 设置可以支持缩放
        setting.setSupportZoom(true);
        // 设置出现缩放工具
        setting.setBuiltInZoomControls(false);
        webView.addJavascriptInterface(WebViewActivity.this,"android");
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                ToastUtil.showShort(message,WebViewActivity.this);
                return super.onJsAlert(view, url, message, result);
            }
        });

        AssetManager asset = this.getAssets();
        try {
            InputStream is = asset.open("DLHGQ003.html");
            Document doc = Jsoup.parse(is, "UTF-8", "");

            // head添加平滑滚动js
            doc.head().append(" <script type = \"text/javascript\"> " +
                    "function elementPosition(obj) { " +
                    "    var curleft = 0, " +
                    "    curtop = 0; " +
                    "    if (obj.offsetParent) { " +
                    "        curleft = obj.offsetLeft; " +
                    "        curtop = obj.offsetTop; " +
                    "        while (obj = obj.offsetParent) { " +
                    "            curleft += obj.offsetLeft; " +
                    "            curtop += obj.offsetTop; " +
                    "        } " +
                    "    } " +
                    "    return { " +
                    "        x: curleft, " +
                    "        y: curtop " +
                    "    }; " +
                    "} " +
                    "var perDes = 0; " +
                    "function ScrollToControl(id) { " +
                    "    alert(\"id:\" + id ); " +
                    "    var elem = document.getElementById(id); " +
                    "    var scrollPos = elementPosition(elem).y; " +
                    "    let scrollTop = document.documentElement.scrollTop || document.body.scrollTop; " +
                    "    scrollPos = scrollPos - scrollTop; " +
                    "    alert(\"scrollPos:\" + scrollPos + \"   scrollTop:\" + scrollTop); " +
                    "    if (scrollPos < 0) { " +
                    "        perDes = -50; " +
                    "    } else { " +
                    "        perDes = 50; " +
                    "    } " +
                    "    var remainder = scrollPos % Math.abs(perDes); " +
                    "    var repeatTimes = (scrollPos - remainder) / perDes; " +
                    "    ScrollSmoothly(repeatTimes, perDes); " +
                    "    window.scrollBy(0, remainder); " +
                    "} " +
                    "var repeatCount = 0; " +
                    "var cTimeout; " +
                    "var timeoutIntervals = new Array(); " +
                    "var timeoutIntervalSpeed; " +
                    "function ScrollSmoothly(repeatTimes, perDes) { " +
                    "    if (repeatCount < repeatTimes) { " +
                    "        window.scrollBy(0, perDes); " +
                    "    } else { " +
                    "        repeatCount = 0; " +
                    "        clearTimeout(cTimeout); " +
                    "        return; " +
                    "    } " +
                    "    repeatCount++; " +
                    "    cTimeout = setTimeout(\"ScrollSmoothly('\"+repeatTimes+\"','\"+perDes+\"')\",10); " +
                    "} </script> ");

            // 设置字体大小
            Element style = doc.select("style").first();
            style.append(" tr{ font-size:14px;} ");

            // 将table的宽度设置为100%
            Elements tableWidth = doc.select("table[width]");
            for (Element element : tableWidth) {
                element.attr("width", "100%");
            }

            // 获取所有tr节点
            Elements trElements = doc.getElementsByTag("tr");
            for (Element element : trElements) {
                Elements tdElements = element.children();

                int childSize = tdElements.size();
                // 计算百分比
                int precent = 100 / childSize;
                int model = 100 % childSize;
                for (int i = 0; i < tdElements.size(); i++) {
                    StringBuffer stringBuffer = new StringBuffer();
                    if (i == 0) { // 第一个
                        int firstPre = precent + model;
                        stringBuffer.append(firstPre);
                        stringBuffer.append("%");
                    } else {
                        stringBuffer.append(precent);
                        stringBuffer.append("%");
                    }
                    tdElements.get(i).attr("width", stringBuffer.toString());
                }

                // 为td添加ID
                if(tdElements.size() == 1 ){
                    Element tdEle = tdElements.get(0);
                    String text = tdEle.text();

                    Pattern pat= Pattern.compile("^d{0,}(\\w+、)[\\u4e00-\\u9fa5]{0,}$");
                    Matcher mat=pat.matcher(text);
                    if(mat.matches()){
                        String sId = text.split("、")[0];
                        StringBuffer stringBuffer = new StringBuffer("base_");
                        stringBuffer.append(sId);
                        idList.add(stringBuffer.toString());
                        tdEle.attr("id",stringBuffer.toString());
                    }
                }
            }
            // 在原有size基础上添加一个虚拟值
            locationArray = new int[idList.size()+1];

            // 增加距离底部高度
            Element lastTable = doc.select("table").last();
            int totalHeight = DisplayUtils.getDisplayHeight(this);
            int statusHeight = DisplayUtils.getStatusBarHeight(this);
            height =  DisplayUtils.px2dip(this,totalHeight) - statusHeight- DisplayUtils.dip2px(this,1) ;
            StringBuffer stringBuffer = new StringBuffer("<div style='color:#00FF00; height:");
            stringBuffer.append(height);
            stringBuffer.append("px'> ");
            stringBuffer.append(lastTable.toString());
            stringBuffer.append(" </div> ");
            //增加body的高度height
            lastTable.select("table").attr("height",height+"px");
            lastTable.remove();
            doc.body().append(stringBuffer.toString());


            doc.body().append(" <script type = \"text/javascript\"> " +
                    "function switchdata(source) { " +
                    "    var list = source; " +
                    "    var result = new Array(list.length); " +
                    "    for (var i = 0; i < list.length; i++) { " +
                    "        var ss = list[i]; " +
                    "        var elem = document.getElementById(ss); " +
                    "        var curtop = 0; " +
                    "        if (elem.offsetParent) { " +
                    "            curtop = elem.offsetTop; " +
                    "            while (elem = elem.offsetParent) { " +
                    "                curtop += elem.offsetTop; " +
                    "            } " +
                    "        } " +
                    "        result[i] = curtop; " +
                    "    } " +
                    "    window.android.jsCallAndroidArgs(result.toString()); " +
                    "} " +
                    "</script> ");

            String afterWeb = doc.toString();
            webView.loadDataWithBaseURL(null, afterWeb, "text/html", "UTF-8", null);

        } catch (IOException e) {
            e.printStackTrace();
        }


        indicatorView.setUpWithLable(idList);
        indicatorView.setOnIndicatorClickListener(new CircleIndicatorView.OnIndicatorClickListener() {
            @Override
            public void onSelected(int position) {
                Log.e(TAG,"idList--->"+idList.get(position));
                // 调用JS
                webView.loadUrl("javascript:ScrollToControl('" +idList.get(position) + "')");
            }
        });

        webView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int currentX, int currentY, int preX, int preY) {
                int curYxdp =DisplayUtils.px2dip(WebViewActivity.this,currentY);
                Log.e(TAG,"滑动监听位置dp："+curYxdp);
                int index = Calculate.binarySearchKey(locationArray,curYxdp);

                Log.e(TAG,"索引位置 ："+index);
                indicatorView.setSelectPosition(index);
            }
        });

    }


    @JavascriptInterface
    public void jsCallAndroid() {
        Log.e(TAG,"调用了jsCallAndroid");
    }

    @JavascriptInterface
    public void jsCallAndroidArgs(String args){

        Log.e(TAG,"js回调Java方法："+args);
        if(!TextUtils.isEmpty(args)&&
                args.contains(",")){
           String[] temp = args.split(",");
           for(int i=0;i< locationArray.length;i++){
               if(i == temp.length) {
                   locationArray[i] = Integer.valueOf(temp[i-1]) + height;
               }else {
                   locationArray[i] = Integer.valueOf(temp[i]);
               }
           }
        }
        Log.e(TAG,"位置数组："+Arrays.toString(locationArray));

    }

}
